import Vue from 'vue'
import Vuex from 'vuex'
import {getRequest} from "./utils/api";
import SockJS from 'sockjs-client'
import Stomp from 'stompjs'
import {Notification} from "element-ui";

Vue.use(Vuex)

const now = new Date();

const store = new Vuex.Store({
    state: {
        routes: [],
        sessions: {},
        admins: [],
        currentAdmin: null,
        currentSession: null,
        filterKey: '',
        stomp: null,
        isDot:{},

    },
    mutations: {
        INIT_CURRENTADMIN(state,admin) {
            state.currentAdmin = admin;
        },
        initRoutes(state, data) {
            state.routes = data;
        },
        changecurrentSession(state, currentSession) {
            state.currentSession = currentSession;
            Vue.set(state.isDot,state.currentAdmin.username+'#'+state.currentSession.username,false);
        },
        addMessage(state, msg) {

            let mss = state.sessions[state.currentAdmin.username + '#' + msg.to];
            if (!mss) {
                //当state.sessions为空时 vue 可以监听它从而是页面发生改变
                Vue.set(state.sessions,state.currentAdmin.username + '#' + msg.to,[])
            }
            state.sessions[state.currentAdmin.username + '#' + msg.to].push({
                content: msg.connect,
                date: new Date(),
                self: !msg.notSelf
            })
        },
        INIT_DATA(state) {
            //从本地空间取历史信息
            let data = localStorage.getItem('vue-chat-session');
            if (data) {
                state.sessions = JSON.parse(data);
            }
        },
        INIT_ADMINS(state, data) {
            state.admins = data;
            state.admins.megs = 0;
        }
    },
    //唯一可以改变state值的方法(异步执行)
    actions: {
        connect: function (context) {
            context.state.stomp = Stomp.over(new SockJS('/ws/ep')) // 连接端点
            let token = window.sessionStorage.getItem('tokenStr')
            context.state.stomp.connect({'Auth-Token': token}, success => { // 把 token 放进去
                context.state.stomp.subscribe('/user/queue/chat', msg => { // 订阅消息频道
                    // console.log(JSON.parse(msg.body));
                    let receiverMsg = JSON.parse(msg.body);
                    if (!context.state.currentSession || receiverMsg.from != context.state.currentSession.username){
                        Notification.info({
                            title: '【' +receiverMsg.fromNickName+ '】发来一条消息',
                            message: receiverMsg.content.length > 10 ? receiverMsg.content.substr(0,10)+'...' : receiverMsg.content,
                            position: 'bottom-right'
                        });
                        context.state.admins.msgs = context.state.admins.msgs+1 ;
                        Vue.set(context.state.isDot,context.state.currentAdmin.username+'#'+receiverMsg.from,true);
                    }
                    receiverMsg.notSelf = true;
                    receiverMsg.to = receiverMsg.from;
                    context.commit('addMessage', receiverMsg);
                })
            }, error => {
                console.log(error);
            })
        },
        initData(context) {
            context.commit('INIT_DATA');
            getRequest('/api/system/admin/').then(resp => {
                if (resp) {
                    context.commit('INIT_ADMINS', resp);
                }
            })

        }
    }
})

store.watch(function (state) {
    return state.sessions
}, function (val) {
    console.log('CHANGE: ', val);
    localStorage.setItem('vue-chat-session', JSON.stringify(val));
}, {
    deep: true/*这个貌似是开启watch监测的判断,官方说明也比较模糊*/
})


export default store;